package com.steven;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import javax.swing.*;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;


public class SingleGetPic {
    static String prefix = "http://q.quantuwang1.com";
    static String outDir = "";
    static String pname = "";
    static int current_album = 0;
    static int personTotal = 0;
    static int albumAmount = 0;
    int count;
    static boolean isDownLoad = false;
    static boolean isErr = false;
    int statusCode;
    static ArrayList<String> all = new ArrayList<>();

    static Elements getElements() {
        // http://m.quantuwang1.com/meinv/daquan/
        String main_site = "http://q.quantuwang1.com/meinv/daquan/";
        SpiderHttpClient main_response = new SpiderHttpClient(main_site, "GET", "UTF-8", null);
        String responseStr = main_response.getResponseStr();
        // body > div.index_c > div > a:nth-child(1)
//        System.out.println(responseStr);
        Document document = Jsoup.parse(responseStr);
        return document.select("body > div.index_c > div > a");
    }

    // 获取所有的人物列表
    public void getAllPersons() {
        Elements elements = getElements();
        for (Element element : elements) {
            all.add(element.text());
        }
    }

    //下载图片
    public boolean getPic(int start, int end) {
        Elements elements = getElements();
        personTotal = elements.size();

        for (int p = start; isDownLoad && p <= end && p < personTotal; p++) {
            count = 0;
            albumAmount = 0;
            PicView.fromField.setText(p + "");
            PicView.toField.setText(end + "");

            Element element = elements.get(p);
            pname = element.text();
            PicView.pname_label.setText("MM名称: " + pname);
            System.out.println("==========================" + pname + "=================================");
            String href = element.attr("href");
            String peer = prefix + href;
            System.out.println(pname + "->" + peer);

            // body > div.box > div > div.index_middle_c > ul > li > a > img
            SpiderHttpClient peer_response = new SpiderHttpClient(peer, "GET", "UTF-8", null);
            String peer_responseResponseStr = peer_response.getResponseStr();
//            System.out.println(peer_responseResponseStr);
            Document peer_responseResponseStr_document = Jsoup.parse(peer_responseResponseStr);
            // body > div.box > div > div.index_middle_c > ul > li:nth-child(40) > a
            Elements peer_responseResponseStr_elements = peer_responseResponseStr_document.select("body > div.box > div > div.index_middle_c > ul > li > a");
            albumAmount = peer_responseResponseStr_elements.size();
            collect(peer_responseResponseStr_elements);
            // body > div.box > div > div.list_page
            Elements list_page = peer_responseResponseStr_document.select("body > div.box > div > div.list_page");
            int childNodeSize = list_page.get(0).childNodeSize();

            for (int i = 1; i < childNodeSize; i++) {
                // <a href="/t/ec3e1c0f10626691.html">2</a>
                Node childNode = list_page.get(0).childNode(1);
               /* int s = childNode.toString().indexOf(">");
                int e = childNode.toString().lastIndexOf("<");
                String nodeName = childNode.toString().substring(s + 1, e);*/
                String next_list = childNode.attr("href");
                String next = prefix + next_list;
                SpiderHttpClient next_response = new SpiderHttpClient(next, "GET", "UTF-8", null);
                String next_responseResponseStr = next_response.getResponseStr();
                Document next_responseResponseStr_document = Jsoup.parse(next_responseResponseStr);
                Elements next_responseResponseStr_elements = next_responseResponseStr_document.select("body > div.box > div > div.index_middle_c > ul > li > a");
                albumAmount += next_responseResponseStr_elements.size();
                collect(next_responseResponseStr_elements);
//                System.out.println(nodeName+"->"+next);
            }
            PicView.albumTotalField.setText(albumAmount + "");
            current_album = 0;
        }
        return isErr;

    }

    // 采集组链接
    private void collect(Elements group_elements) {
        for (Element group : group_elements) {
            if (isErr) {
                break;
            }
            String href_img = group.attr("href");
            Element child = group.child(0);
            String group_name = child.attr("alt");
            PicView.album.setText(group_name);

            String img_href = prefix + href_img;
            System.out.println(group_name.replace(" ", "_") + "->" + img_href);
            computePageAndGetPic(img_href, group_name);

        }
    }

    // body > div:nth-child(6) > div > div.index_c_img > a > img
    // body > div:nth-child(6) > div > div.index_c_page
    private void computePageAndGetPic(String img_href, String group_name) {
        if (++count < current_album) {
            System.out.println("跳过专辑" + count);
            return;
        }
        PicView.albumIndexField.setText((current_album +1) + "");
        ++current_album;
        SpiderHttpClient img_href_response = new SpiderHttpClient(img_href, "GET", "UTF-8", null);
        String img_href_responseStr = img_href_response.getResponseStr();
        Document img_href_responseResponseStr_document = Jsoup.parse(img_href_responseStr);
        // 获取页码
        Elements img_href_responseResponseStr_elements = img_href_responseResponseStr_document.select("body > div > div > div.index_c_page");
        int page = img_href_responseResponseStr_elements.get(0).childNodeSize();
        // 获取图片
        Elements img_responseResponseStr_elements = img_href_responseResponseStr_document.select("body > div > div > div.index_c_img > a > img");
        // http://d.duotuwang.com/2021/03/24/24551/1.jpg
        String src = img_responseResponseStr_elements.get(0).attr("src");
        int sep = src.lastIndexOf("/");
        String pre = src.substring(0, sep + 1);
//        boolean out=false;
        for (int i = 1; i <= page; i++) {
            if (isErr) {
                break;
            }

            PicView.index.setText(i + "-->" + (statusCode == 200 ? "下载成功" : String.valueOf(statusCode)));
            String rel = pre + (i + ".jpg");
            out(rel, group_name, i);

            // 每张下载完,休息1s
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            System.out.println(rel);
        }
        // 每一组下载完,休息10s
        if (!isErr) {
            try {
                PicView.album.setText("休息10s......");
                PicView.index.setText("");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    // 写出
    private void out(String peer, String group_name, int index) {
        LinkedHashMap<String, String> request_headers = new LinkedHashMap<>();
        request_headers.put("Host", "qq.quantuwang1.com");
        request_headers.put("Cookie", "__51uvsct__Jdk3ZTNaBLEVySmC=1; __51vcke__Jdk3ZTNaBLEVySmC=17dff588-fd90-53b2-aba6-be8b32d65907; __51vuft__Jdk3ZTNaBLEVySmC=1656216223266; sttttmlusername=942693; sttttmluserid=3237; sttttmlgroupid=2; sttttmlrnd=NstQ9KaHE7jz3kb5c4dK; sttttmlauth=e171a2e8b2d4ebb68a25edcd589cf8c4; __vtins__Jdk3ZTNaBLEVySmC=%7B%22sid%22%3A%20%220d84086b-7266-54fc-891f-a104d72c9d04%22%2C%20%22vd%22%3A%2037%2C%20%22stt%22%3A%20368466%2C%20%22dr%22%3A%204382%2C%20%22expires%22%3A%201656218391729%2C%20%22ct%22%3A%201656216591729%7D");
        request_headers.put("Referer", "http://qq.quantuwang1.com");
        request_headers.put("Upgrade-Insecure-Requests", "1");
//                System.out.println(ref);
//        request_headers.put("Referer",peer);
//        request_headers.put("Sec-Fetch-Site","cross-site");
//        request_headers.put("Sec-Fetch-Dest","image");
        request_headers.put("Connection", "keep-alive");
        request_headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 Edg/92.0.902.67");
        Header[] headers = new Header[request_headers.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : request_headers.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            BasicHeader basicHeader = new BasicHeader(key, value);
            headers[i++] = basicHeader;
        }
//        SpiderHttpClient peer_next = new SpiderHttpClient(peer,"GET","GBK",null,request_headers);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(peer);
//        httpGet.setHeaders(headers);
        try {
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

            statusCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println(statusCode);
            if (statusCode == 200) {
                HttpEntity entity = httpResponse.getEntity();


                File file = new File(outDir + File.separator + pname.replace(" ", "_") + File.separator + group_name.replace(" ", "_"));
                if (!file.exists()) {
                    file.mkdirs();
                }

                FileOutputStream fos = new FileOutputStream(outDir + File.separator + pname.replace(" ", "_") + File.separator + group_name.replace(" ", "_") + File.separator + index + ".jpg");
                if (entity != null) {
                    entity.writeTo(fos);
                    fos.flush();
                    fos.close();
                    System.out.println(group_name + File.separator + index + ".jpg ---> 写出成功!");
                } else {
                    System.out.println("null>>>>>>>>>>>>>>");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(PicView.jFrame, "发生了一些小问题,停下来看一看吧!");
            isErr = true;
            PicView.stopPD();

        }
    }
}

